package com.webchat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.utils.JarTool;
import okhttp3.*;
import okio.ByteString;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.time.LocalTime;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class WebChatTest {
    private static OkHttpClient client = null;
    private static WebSocket mWebsocket = null;
    private static Integer status = 0;


    static {
        client = new OkHttpClient().newBuilder().build();
    }

    public static void main(String[] args) throws Exception {
        if(args == null || args.length == 0){
            System.err.println("请传入参数Token");
            return;
        }

        connect(args[0]);

//        if(args[0] != null){
//            System.out.println(JarTool.getJarDir());
//            System.out.println();
//            System.out.println(JarTool.getJarPath());
//            System.out.println();
//            System.out.println(JarTool.getJarPath().split("file:")[0]);
//            System.out.println();
//            System.out.println(JarTool.getJarName());
//            System.out.println();
//            System.out.println(WebChatTest.class.getResource("").getPath());
//
//            return;
//        }
    }

    private static void connect(String arg) {
        String url = String.format("wss://chat.pingme.tel/webchat/?token=%s&EIO=3&transport=websocket", arg);

        System.out.println("连接中...");
        Request request = new Request.Builder()
                .url(url)
                .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36")
                .header("Origin", "https://messages.pingme.tel")
                .header("Host", "chat.pingme.tel")
                .build();

        for (String name : request.headers().names()) {
            System.out.printf("\treq header %s -> %s\n", name, request.headers().get(name));
        }
        System.out.println("----------------\n");

        client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                mWebsocket = webSocket;
                System.out.println("连接成功: " + url);
                status = 1;

                for (String name : response.headers().names()) {
                    System.out.printf("\tresp header %s -> %s\n", name, response.headers().get(name));
                }
            }

            @Override
            public void onMessage(WebSocket webSocket, String str) {
                super.onMessage(webSocket, str);
                handler(webSocket, str);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                super.onMessage(webSocket, bytes);

                System.out.println("------- 收到byte消息：" + new String(bytes.toByteArray()));
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                super.onClosed(webSocket, code, reason);
                System.out.printf("关闭 code(%s) reason(%s)\n", code, reason);
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                super.onClosing(webSocket, code, reason);
                System.out.println("关闭中: " + reason);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                super.onFailure(webSocket, t, response);
                System.out.println("连接失败: websocket" + t.toString());
                mWebsocket = null;
                --status;

                if(response != null){
                    for (String name : response.headers().names()) {
                        System.out.printf("\tresp header %s -> %s\n", name, response.headers().get(name));
                    }
                }

                if(status <= -3){
                    System.err.printf("尝试【%s】仍连不上 放弃", Math.abs(status));
                    return;
                }

                System.out.printf("3秒后尝试第【%s】次重新连接", Math.abs(status));
                try { TimeUnit.SECONDS.sleep(3); }catch (Exception e){}
                connect(arg);
            }
        });
    }

    private static final ScheduledExecutorService scheduled = new ScheduledThreadPoolExecutor(1);
    private static ScheduledFuture<?> stepFuture = null;
    private static JSONObject config = new JSONObject();

    private static void handler(WebSocket webSocket, String str) {
        if(str == null || str.length() == 0){
            return;
        }


        System.out.printf("-------%s 收到str消息：%s\n", LocalTime.now().toString(), str);
        if(str.startsWith("0{")){
            config = JSON.parseObject(str.substring(1));
            return;
        }

        if("40".equals(str)){
            Integer pingInterval = config.getInteger("pingInterval");
            stepFuture = scheduled.scheduleAtFixedRate(() -> webSocket.send("2"), pingInterval, pingInterval, TimeUnit.MILLISECONDS);
            return;
        }

        if(str.startsWith("42")){
            try {
                JSONArray msg = JSON.parseArray(str.substring(2));

                String path = JarTool.getJarPath().split("file:")[0];
                File file = new File( path + "data.txt");

                if(!file.exists()){
                    System.out.println("创建文件：" + file.getPath());
                    file.createNewFile();
                }

                FileUtils.write(file, (msg + "\r"), true);
                System.out.println("已保存！");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
